package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Api(tags = "C端菜品相关接口")
@Slf4j
public class DishController {
    @Autowired
    private ValueOperations valueOperations;
    @Autowired
    DishService dishService;
    @GetMapping("/list")
    @ApiOperation("根据id查询菜品")
    public Result<List<DishVO>> getById(Long categoryId){
        log.info("根据分类id查询菜品：{}", categoryId);
        //查找redis中是否存在菜品数据
        String key = "dish_" + categoryId;
        List<DishVO> dishVOS = (List<DishVO>) valueOperations.get(key);
        if (dishVOS != null && dishVOS.size() > 0){
            return Result.success(dishVOS);
        }
        //查询启售中的菜品
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);
        //如果不存在，查询数据库
        dishVOS = dishService.getCategoryByIdWithFlavor(dish);
        //将查询结果放入redis
        valueOperations.set(key, dishVOS, 10, TimeUnit.MINUTES);
        return Result.success(dishVOS);
    }


}
